package com.hsxxherp.ation.business.user.center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.ation.business.user.center.entity.UcUserEntity;
import com.hsxxherp.ation.business.user.center.mapper.UcUserMapper;
import com.hsxxherp.ation.business.user.center.service.IUcUserService;
import com.hsxxherp.ation.business.user.center.util.Sha256PasswordEncoder;
import com.hsxxherp.ation.business.user.dto.LoginByEmailRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 用户管理实现类
 *
 * @author Antonio 《2486970363@qq.com》
 * @since 2024年6月24日
 */
@Service
public class UcUserServiceImpl extends ServiceImpl<UcUserMapper, UcUserEntity> implements IUcUserService {

    private static final Logger log = LoggerFactory.getLogger(UcUserServiceImpl.class);

    /**
     *
     */
    private final Sha256PasswordEncoder encoder = new Sha256PasswordEncoder();

    @Override
    public boolean saveUSer(Map<String, Object> params) {
        UcUserEntity ucUser = getUcUserEntity(params);
        log.info("【添加用户】：{}", ucUser.toString());
        return baseMapper.insert(ucUser) > 0;
    }

    /**
     * 构建新增实体
     *
     * @param params
     * @return
     */
    private UcUserEntity getUcUserEntity(Map<String, Object> params) {
        UcUserEntity ucUserEntity = new UcUserEntity();
        if (params.get("user_code") != null) {
            ucUserEntity.setUserCode(params.get("user_code").toString());
        }
        if (params.get("user_name") != null) {
            ucUserEntity.setUserName(params.get("user_name").toString());
        }
        if (params.get("email") != null) {
            ucUserEntity.setEmail(params.get("email").toString());
        }

        if (params.get("password") != null) {
            ucUserEntity.setPassword(encoder.encode(params.get("password").toString()));
        }
        return ucUserEntity;
    }

    /**
     * 如果登录成功则返回用户info，失败返回null
     *
     * @param loginByEmailRequest
     * @return
     */
    @Override
    public boolean loginByEmail(LoginByEmailRequest loginByEmailRequest) {
        LambdaQueryWrapper<UcUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UcUserEntity::getEmail, loginByEmailRequest.getEmail());
        UcUserEntity ucUserEntity = baseMapper.selectOne(queryWrapper);

        return ucUserEntity != null && ucUserEntity.getPassword().equals(loginByEmailRequest.getPassword());
    }
}
